<?php
namespace app\admin\controller;


use app\admin\model\RoleModel;
use app\admin\model\UserModel;
use app\admin\model\DepartmentModel;

class User extends Base
{
    //用户列表
    public function index()
    {
        if(request()->isAjax()){
            $param = input('param.');
            $limit = $param['pageSize'];
            $offset = ($param['pageNumber'] - 1) * $limit;
            $where = [];
			$whereOr = [];
            if (!empty($param['searchText'])) {
				$whereOr = [
					'user_name' => $param['searchText'],
					'real_name' => $param['searchText']
				];
            }
            $user = new UserModel();
            $data['rows'] = $user->getUsersByWhere($where,$whereOr,$offset,$limit);
			$data['total'] = $user->getAllUsers($where,$whereOr);
            $status = config('user_status');
            // 拼装参数
            foreach($data['rows'] as &$vo){
                $vo['last_login_time'] = date('Y-m-d H:i:s', $vo['last_login_time']);
                $vo['status'] = $status[$vo['status']];
            }
			return ['code'=>1,'msg'=>'加载成功','data'=>$data];
        }
        return $this->fetch();
    }

	/**
	 * [添加用户]
	 */
    public function userAdd(){
        if(request()->isPost()){
            $param = input('post.');
            $param['password'] = md5($param['password'] . config('salt'));
            $user = new UserModel();
            $flag = $user->insertUser($param);
            return json(msg($flag['code'], $flag['data'], $flag['msg']));
        }
        $role = new RoleModel();
        $this->assign([
            'role' => $role->getRole(),
            'status' => config('user_status')
        ]);
        return $this->fetch();
    }

    // 编辑用户
    public function userEdit()
    {
        $userModel = new UserModel();
        if(request()->isPost()){
            $param = input('post.');
            if(empty($param['password'])){
                unset($param['password']);
            }else{
                $param['password'] = md5($param['password'] . config('salt'));
            }
            $flag = $userModel->editUser($param);
            return json(msg($flag['code'], $flag['data'], $flag['msg']));
        }
        $id = input('param.id');
        $roleModel = new RoleModel();
		$departModel = new DepartmentModel();
		$user = $userModel->getOneUser($id);
		$user['depart_name'] = $departModel->where('id',$user['depart_id'])->value('name');
        $this->assign([
            'user' => $user,
            'status' => config('user_status'),
            'role' => $roleModel->getRole()
        ]);
        return $this->fetch();
    }

    // 删除用户
    public function userDel(){
        $id = input('param.id');
        $role = new UserModel();
        $flag = $role->delUser($id);
        return json(msg($flag['code'], $flag['data'], $flag['msg']));
    }
}
